import {View, Text} from "@tarojs/components";
import {Button, Cell, Field, Image} from "@antmjs/vantui";
import {useCallback, useEffect, useRef, useState} from "react";
import Utils from "@/utils/common";
import AssetImage from "@/common/AssetImage";
import RouthPath from "@/common/RouthPath";
import LocalUtils from "@/utils/local_utils";
import {loginApi} from "@/common/apis/home_datasource";
import httpUtils from "@/common/httpRequest";


export default function LoginPhone() {

  useEffect(() => {
    Utils.setTitle("登录")
  }, []);
  const [phone, setPhone] = useState()
  const [pwd, setPwd] = useState()
  const [code, setCode] = useState()
  const [code1, setCode1] = useState()

  const [countdown, setCountdown] = useState(0); // 倒计时时间
  const [isSending, setIsSending] = useState(false); // 发送状态


  const [isPwdLogin, setIsPwdLogin] = useState(true)

  const uuid = useRef(Utils.generateUuidV4());
  const handleSendCode = () => {
    if (!phone) {
      Utils.showToast({title: '请输入手机号', icon: 'none'});
      return;
    }
    // 模拟发送验证码
    console.log('发送验证码到:', phone);

    // 设置倒计时时间为60秒
    setCountdown(60);
    setIsSending(true);
  };
  useEffect(() => {
    let timer: NodeJS.Timeout | null = null;

    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown(prevCountdown => prevCountdown - 1);
      }, 1000);
    } else {
      setIsSending(false);
    }

    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [countdown]);


  useEffect(() => {
    // const router = Taro.getCurrentInstance().router
    // if (router) {
    //   const params = Utils.getParamsWithUrl(router.params)
    //   if (params) {
    //     setIsPwdLogin(params.isPwd)
    //   }
    // }

  }, []);


  return (
    <View style={{
      display: 'flex',
      height: '100VH',
      flexDirection: 'column',
      alignItems: 'center',
      background: `linear-gradient(to bottom, ${AssetImage.colorEbf0fd}, white)`
    }}
    >
      <View style={{
        flex: 1,
        display: 'flex',
        alignItems: 'center',
        width: '100%',
        flexDirection: 'column',
        justifyContent: 'center',
      }}
      >
        <View style={{
          display: 'flex',
          width: '100%',
          flexDirection: 'column',
          '--cell-background-color': 'transparent',
        }}
        >
          <Cell title='Hello!' border={false} titleStyle={{fontSize: '32px', fontWeight: 'bold'}}/>
          <Cell title='欢迎来到管理端平台' border={false} titleStyle={{fontSize: '20px'}}/>
          <View style={{margin: '10px 20px', backgroundColor: 'white', borderRadius: '25px'}}>
            <Field
              value={phone}
              placeholder='请输入用户名'
              type='text'
              border={false}
              onChange={(e) => setPhone(e.detail)}
            />
          </View>
          {
            isPwdLogin ? <View style={{margin: '10px 20px', backgroundColor: 'white', borderRadius: '25px'}}>
              <Field
                value={pwd}
                placeholder='请输入密码'
                type='password'
                border={false}
                onChange={(e) => setPwd(e.detail)}
              />
            </View> : <View style={{margin: '10px 20px', backgroundColor: 'white', borderRadius: '25px'}}>
              <Field
                center
                clearable
                placeholder='请输入短信验证码'
                border={false}
                type='number'
                value={code}
                onChange={(e) => setCode(e.detail)}
                renderButton={
                  <Button
                    size='small'
                    type='primary'
                    disabled={isSending || countdown > 0}
                    onClick={handleSendCode}
                  >
                    {isSending || countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
                  </Button>
                }
              />
            </View>
          }
          <View style={{margin: '10px 20px', backgroundColor: 'white', borderRadius: '25px'}}>
            <Field
              center
              clearable
              placeholder='请输入验证码'
              border={false}
              type='text'
              value={code1}
              onChange={(e) => setCode1(e.detail)}
              renderButton={
                <Captcha uuid={uuid.current}/>
              }
            />
          </View>
          {/*<View style={{display: 'flex', justifyContent: 'flex-end', marginRight: '30px'}}>*/}
          {/*  <Text style={{color: AssetImage.themeColor}} onClick={() => {*/}
          {/*    setIsPwdLogin(!isPwdLogin)*/}
          {/*  }}*/}
          {/*  >*/}
          {/*    {isPwdLogin ? '忘记密码?试试验证码登录' : '返回密码登录'}*/}
          {/*  </Text>*/}
          {/*</View>*/}
          <View style={{margin: '20px'}}>
            <Button type='primary' block onClick={() => {
              //判断phone code pwd 不能为空
              if (!Utils.isNotBlank(phone) || !Utils.isNotBlank(pwd) || !Utils.isNotBlank(code1)) {
                Utils.showToast({title: '请输入用户名，密码和验证码', icon: 'none'});
                return;
              }
              loginApi({
                username: phone,
                captcha: code1,
                password: pwd,
                uuid: uuid.current
              }).then((res) => {
                if (res) {
                  LocalUtils.setToken(res.token)
                  Utils.reLaunch({
                    url: RouthPath.index
                  })
                }
              })

            }}
            >
              登录
            </Button>
          </View>
        </View>
      </View>
      <View style={{justifySelf: 'flex-end', margin: '20px'}}>
        <Text style={{fontSize: '12px', color: AssetImage.themeColor}}>苏ICP备2024115938号-1</Text>
      </View>
    </View>
  )
}


function Captcha(props) {
  const [imageUrl, setImageUrl] = useState<string>();
  const captchaUrl = useCallback(() => {
    const url = httpUtils.urlWithPath(Utils.buildUrlWithParams('/captcha', {
      uuid: props.uuid,
      timestamp: Utils.generateUuidV4()
    }));
    setImageUrl(url)
  }, [props.uuid]);
  useEffect(() => {
    captchaUrl()
  }, [captchaUrl]);
  return (
    <View onClick={() => {
      captchaUrl()
    }}>
      <Image src={imageUrl ? imageUrl : ''} style={{width: '100px', height: '30px'}} />
    </View>
  )
}


